package com.asialjim.wechat.message.handler;

import com.asialjim.wechat.message.WeChatMessage;
import com.asialjim.wechat.message.WeChatMessageHandler;
import com.asialjim.wechat.message.output.WeChatOutputMessage;
import com.asialjim.wechat.msgcrypt.WxBizMsgCryptService;
import com.asialjim.wechat.pojo.account.WeChatAccount;
import com.asialjim.wechat.pojo.account.WeChatAccountHolder;
import com.asialjim.wechat.pojo.account.WeChatAccountMessageEncodingType;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.util.Objects;

/**
 * <h1><em>ASIAL JIM JAVA DOC</em></h1><hr/>
 * <h2>CLASS DESCRIPTION <i>[ NAME: DefaultWeChatMessageHandler ]</i></h2><strong>
 * <p> base default we-chat message handler
 * </strong><p><p><em>Copyright &copy; Asial Jim Co., LTD</em><hr/>
 *
 * @author Asial Jim &nbsp;&nbsp; <span>Email:<a href="mailto:asialjim@hotmail.com">asialjim@hotmail.com</a> &nbsp;&nbsp; <a href="asialjim@qq.com">asialjim@qq.com</a></span>
 * @version 1.0.0
 * @since 2021/3/11   &nbsp;&nbsp; JDK 8
 */
@Slf4j
@AllArgsConstructor
public class DefaultWeChatMessageHandler implements WeChatMessageHandler{
    private final WxBizMsgCryptService cryptService;

    protected WeChatOutputMessage output(WeChatMessage callMessage){
        log.info("\r\n\tDEFAULT MESSAGE HANDLER EXECUTE: HANDLE MESSAGE:[{}]",callMessage);
        return null;
    }

    @Override
    public String handle(WeChatMessage weChatMessage, String signature, String timestamp, String nonce, String echostr) {
        // TODO 用户开启人工客服时前置处理


        WeChatOutputMessage output = output(weChatMessage);
        if (Objects.nonNull(output)) {
            output.setCreateTime(weChatMessage.getCreateTime());
            output.setFromUserName(weChatMessage.getToUserName());
            output.setToUserName(weChatMessage.getFromUserName());
        }
        log.info("\r\n\tHANDLE WE-CHAT MESSAGE:\r\n\t\t【{}】\r\n\tHANDLER NAME:\r\n\t\t【{}】\r\n\tRESULT:\r\n\t\t【{}】",weChatMessage,messageTypeName(),output);
        return parse2Xml(output,signature,timestamp,nonce);
    }

    @Override
    public String messageTypeName() {
        return "DEFAULT";
    }

    protected String parse2Xml(WeChatOutputMessage outputMessage,String signature, String timestamp, String nonce){
        if (Objects.nonNull(outputMessage)){
            WeChatAccount weChatAccount = WeChatAccountHolder.get();
            WeChatAccountMessageEncodingType encodingType = WeChatAccountMessageEncodingType.nameOf(weChatAccount.getEncodingType());
            if (WeChatAccountMessageEncodingType.PLAINTEXT.equal(encodingType)) {
                return outputMessage.parse2Xml();
            }
            return cryptService.encrypt(outputMessage, weChatAccount, outputMessage.parse2Xml(), signature, timestamp, nonce);
        }
        log.warn("\r\n\tHANDLE WE-CHAT INPUT MESSAGE EXCEPTION:[RESULT IS NULL]");
        return "success";
    }
}